package com.easy.framework.security.handler;

import com.easy.framework.common.constant.I18NConstants;
import com.easy.framework.common.model.R;
import com.easy.framework.common.utils.I18NUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint {


    @Override
    @SneakyThrows
    public void commence(HttpServletRequest request,
                         HttpServletResponse response,
                         AuthenticationException exception) throws IOException {

        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        response.setStatus(HttpStatus.UNAUTHORIZED.value());

        String errorMessage = I18NUtils.message(I18NConstants.AUTHENTICATION_UNAUTHORIZED);
        if (exception instanceof UsernameNotFoundException) {
            errorMessage = I18NUtils.message(I18NConstants.AUTHENTICATION_USERNAME_NOT_FOUND);
        } else if (exception instanceof BadCredentialsException) {
            errorMessage = I18NUtils.message(I18NConstants.AUTHENTICATION_BAD_CREDENTIALS);
        } else if (exception instanceof LockedException) {
            errorMessage = I18NUtils.message(I18NConstants.AUTHENTICATION_LOCKED);
        } else if (exception instanceof DisabledException) {
            errorMessage = I18NUtils.message(I18NConstants.AUTHENTICATION_DISABLED);
        } else if (exception instanceof AccountExpiredException) {
            errorMessage = I18NUtils.message(I18NConstants.AUTHENTICATION_ACCOUNT_EXPIRED);
        } else if (exception instanceof CredentialsExpiredException) {
            errorMessage = I18NUtils.message(I18NConstants.AUTHENTICATION_CREDENTIALS_EXPIRED);
        } else if (exception instanceof OAuth2AuthenticationException) {
            errorMessage = I18NUtils.message(I18NConstants.AUTHENTICATION_CREDENTIALS_EXPIRED);
        }

        response.getWriter().write(new ObjectMapper().writeValueAsString(R.fail(HttpStatus.UNAUTHORIZED.value(),errorMessage)));
    }
}